package com.github.ilioili.justdoit.components.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.ilioili.justdoit.components.fragment.MonthViewFragment;
import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.common.AppBaseActivity;
import com.github.ilioili.justdoit.common.config.AnimationConfig;
import com.github.ilioili.justdoit.common.config.EventConstants;
import com.github.ilioili.justdoit.components.fragment.ChartFragment;
import com.github.ilioili.justdoit.model.dao.RecordDao;
import com.github.ilioili.justdoit.model.dao.ScheduleEventDao;
import com.github.ilioili.justdoit.model.pojo.EventRecord;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.util.AniUtil;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.util.DateUtil;
import com.github.ilioili.justdoit.util.sql.SqlCallback;
import com.github.ilioili.justdoit.widget.CircleAnimationFrame;
import com.github.ilioili.justdoit.widget.PlayViewPager;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;
import com.taihe.template.base.util.SizeUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Layout(R.layout.activity_detail)
public class DetailActivity extends AppBaseActivity {
    public static final String INTENT_KEY_X_LOC = "x";
    public static final String INTENT_KEY_Y_LOC = "y";
    private static final String INTENT_KEY_DATA_ITEM = "DATA_ITEM";
    public static final String INTENT_KEY_EXTEND = "extend";
    public static final int ANIMATION_DURATION = 500;
    @Id(R.id.viewPager)
    private ViewPager viewPager;
    @Id(R.id.tabLayout)
    private TabLayout tabLayout;
    @Id(R.id.toolbar)
    private Toolbar toolbar;
    @Id(R.id.circle_animation_frame)
    private CircleAnimationFrame circleAnimationFrame;
    @Id(R.id.content_view)
    private View vContentView;
    @Id(R.id.fab)
    private View vFab;
    @Id(R.id.playViewPager)
    private PlayViewPager playViewPager;
    private ScheduleEvent scheduleEvent;
    private ChartFragment chartFragment;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.detail, menu);
        return true;
    }

    public void onClickDelete(MenuItem item) {
        Snackbar snackbar = Snackbar.make(viewPager, "删除\"" + scheduleEvent.name + "\"的所有记录吗", Snackbar.LENGTH_LONG);
        snackbar.setAction(R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScheduleEventDao.delete(scheduleEvent);
                finish();
            }
        });
        snackbar.show();
    }

    public void onClickEdit(MenuItem v) {
        startActivityForResult(CreateOrModifyActivity.newIntent(this, scheduleEvent, viewPager.getWidth(), 0, CompatUtil.getColor(this, R.color.colorAccent)), REQUEST_CODE_FRESH_DATA);
        overridePendingTransition(0, 0);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        scheduleEvent = (ScheduleEvent) getIntent().getSerializableExtra(INTENT_KEY_DATA_ITEM);
        chartFragment = (ChartFragment) getSupportFragmentManager().findFragmentById(R.id.circle_fragment);
        setUpUi();
    }

    private void setUpUi() {
        PagerAdapter adapter = viewPager.getAdapter();
        if (null == adapter) {
            adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
                @Override
                public void startUpdate(ViewGroup container) {
                    viewPager.requestLayout();//解决HeadTabPagerWrappper 的 BUG 导致无法自动刷新问题
                }

                @Override
                public Fragment getItem(int position) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date(scheduleEvent.startTime));
                    int month = calendar.get(Calendar.MONTH);
                    int year = calendar.get(Calendar.YEAR);
                    year += position / 12;
                    month += position % 12;
                    if (month > 11) {
                        month -= 12;
                        year++;
                    }
                    MonthViewFragment monthViewFragment = MonthViewFragment.newInstance(scheduleEvent, year, month);
                    monthViewFragment.setOnDataChangedListener(new MonthViewFragment.OnDataChangedListener() {
                        @Override
                        public void onDataChanged() {
                            chartFragment.updateCircleInfo(scheduleEvent);
                        }
                    });
                    return monthViewFragment;
                }

                @Override
                public int getCount() {
                    Calendar calendar = Calendar.getInstance();
                    int curMonth = calendar.get(Calendar.MONTH);
                    int curYear = calendar.get(Calendar.YEAR);
                    calendar.setTime(new Date(scheduleEvent.startTime));
                    int startMonth = calendar.get(Calendar.MONTH);
                    int startYear = calendar.get(Calendar.YEAR);
                    return 12 * (curYear - startYear) + curMonth - startMonth + 1;
                }

                @Override
                public CharSequence getPageTitle(int position) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date(scheduleEvent.startTime));
                    int month = calendar.get(Calendar.MONTH);
                    int year = calendar.get(Calendar.YEAR);
                    year += position / 11;
                    month += position % 11;
                    if (month > 11) {
                        month -= 11;
                        year++;
                    }
                    month += 1;
                    String monthStr = month < 10 ? "-0" + month : "-" + month;
                    return year + monthStr;
                }

                @Override
                public int getItemPosition(Object object) {
                    return POSITION_NONE;
                }
            };
            viewPager.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }

        tabLayout.setupWithViewPager(viewPager);
        toolbar.setTitle(scheduleEvent.name);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int[] loc = new int[2];
                v.getLocationInWindow(loc);
                getIntent().putExtra(INTENT_KEY_X_LOC, loc[0] + v.getMeasuredWidth() / 2);
                getIntent().putExtra(INTENT_KEY_Y_LOC, loc[1] + v.getMeasuredHeight() / 2);
                finish();
            }
        });
        vContentView.setBackgroundColor(scheduleEvent.color);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (getIntent().getBooleanExtra(INTENT_KEY_EXTEND, false)) {
            int locationX = getIntent().getIntExtra(INTENT_KEY_X_LOC, 0);
            int locationY = getIntent().getIntExtra(INTENT_KEY_Y_LOC, 0);
            int foreGroundColor = scheduleEvent.color;
            circleAnimationFrame.expand(true, locationX, locationY, AnimationConfig.MEDIUM, foreGroundColor);
        }
        viewPager.setCurrentItem(adapter.getCount() - 1);
        chartFragment.updateCircleInfo(scheduleEvent);

    }

    @Override
    public void finish() {
        if (getIntent().getBooleanExtra(INTENT_KEY_EXTEND, false)) {
            int locationX = getIntent().getIntExtra(INTENT_KEY_X_LOC, 0);
            int locationY = getIntent().getIntExtra(INTENT_KEY_Y_LOC, 0);
            circleAnimationFrame.collapse(true, locationX, locationY, AnimationConfig.MEDIUM, true, new CircleAnimationFrame.CompleteListener() {
                @Override
                public void onComplete() {
                    DetailActivity.super.finish();
                    overridePendingTransition(0, 0);
                }
            });
        } else {
            super.finish();
        }
    }

    public static Intent newIntent(Context activity, ScheduleEvent scheduleEvent, int xLocationInWindow, int yLocationInWindow) {
        Intent intent = new Intent(activity, DetailActivity.class);
        intent.putExtra(INTENT_KEY_DATA_ITEM, scheduleEvent);
        intent.putExtra(INTENT_KEY_X_LOC, xLocationInWindow);
        intent.putExtra(INTENT_KEY_Y_LOC, yLocationInWindow);
        intent.putExtra(INTENT_KEY_EXTEND, true);
        return intent;
    }

    public void onClickFloatingActionButton(View v) {
        AniUtil.dropDownFloatingBtn(vFab);
        startToPlay();
    }

    private void startToPlay() {
        RecordDao.getList(scheduleEvent.id, new SqlCallback<List<EventRecord>>() {
            @Override
            public void onSucess(List<EventRecord> eventRecordList) {
                final ArrayList<String> list = new ArrayList<>();
                int totalDay = getTotalDay();
                int totalMatchDay = DateUtil.getTotalMatchedDayNum(scheduleEvent, System.currentTimeMillis());
                int completeNum = getCompleteNum(eventRecordList);
                int uncompleteNum = totalMatchDay - completeNum;
                int makeUpNum = getMakeUpNum(eventRecordList);
                int failInHalfNum = getFailInHalfNum(eventRecordList);
                int busyNum = getBuzyNum(eventRecordList);
                int lazyNum = getLazyNum(eventRecordList);
                int forgetNum = uncompleteNum - failInHalfNum - busyNum - lazyNum;

                if (totalDay < 2) {
                    list.add("你才刚刚开始\n坚持一段时间再看我哦");
                } else {
                    list.add(scheduleEvent.name);
                    list.add(new SimpleDateFormat("从yyyy-MM-dd开始").format(scheduleEvent.startTime));
                    list.add("总共 " + totalDay + "天");
                    list.add("任务总数" + totalMatchDay + "次");
                    list.add("完成任务" + completeNum + "次");
                    if (makeUpNum != 0) {
                        list.add("补上任务" + makeUpNum + "次");
                        list.add("不管怎样,迟到总比没到好");
                    }
                    if (uncompleteNum == totalMatchDay && uncompleteNum > 10) {
                        list.add("一次都不漏\n执行力高的难以置信");
                    }
                    if (uncompleteNum != 0) {
                        String str = "未能完成任务" + uncompleteNum + "次";
                        list.add(str);
                        if (uncompleteNum * 1f / totalMatchDay > 0.8f) {
                            str = "\n不过依然看好你哦";
                        } else if (uncompleteNum * 1f / uncompleteNum > 0.5f) {
                            str = "\n至少你坚持的天数过半了";
                        } else if (uncompleteNum == totalMatchDay) {
                            str = "\n你还有救么，亲！？";
                        }
                        list.add(str);
                    }
                    if (0 != failInHalfNum) {
                        String str = "半途而废" + failInHalfNum + "次";
                        list.add(str);
                        if (failInHalfNum * 1f / totalMatchDay > 0.3f) {
                            str = "啥都不说了，你需要努力!";
                        } else {
                            str = "次数不多，再接再厉哦";
                        }
                        list.add(str);
                    }
                    if (0 == lazyNum) {
                        list.add("一次故意偷懒都没有!\n你确定没有欺骗自己么\n反正我是不信");
                    } else {
                        list.add("任性的偷懒" + lazyNum + "次");
                    }
                    if (0 != busyNum) {
                        list.add("有" + busyNum + "次你忙。。。");
                    }
                    if (0 != forgetNum) {
                        list.add("有" + forgetNum + "次你忘了。。。");
                    }
                    list.add("根据人工智能的评估");
                    if (completeNum * 1f / totalMatchDay > 0.8) {
                        list.add("你的执行力爆表\nONE DAY U WILL BE THE MAN!");
                    } else if (completeNum * 1f / totalDay > 0.4) {
                        list.add("别放弃,你还有救！\nKEEP ON!");
                    } else {
                        list.add("你太懒没得救了\nMAY GOD BLESS U !");
                    }
                    list.add("完-OVER");

                }


                playViewPager.setOffscreenPageLimit(list.size());
                playViewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
                    @Override
                    public void transformPage(View page, float position) {
                        if (position < 0) {
                            page.setAlpha(1 + position / list.size());
                            page.setTranslationX(-position * playViewPager.getMeasuredWidth());
                            page.setTranslationY((float) ((-0.2f * Math.sqrt(-position)) * playViewPager.getMeasuredHeight()));
                        } else if (position > 0) {
                            page.setTranslationY(0.7f * position * playViewPager.getMeasuredHeight());
                            page.setTranslationX(-position * playViewPager.getMeasuredWidth());
                        }
                        if (Math.abs(position) < 2) {
                            page.setScaleX(3 - Math.abs(position));
                            page.setScaleY(3 - Math.abs(position));
                        } else {
                            page.setScaleX(1);
                            page.setScaleY(1);
                        }

                    }

                });
                playViewPager.setAdapter(new PagerAdapter() {
                    @Override
                    public int getCount() {
                        return list.size();
                    }

                    @Override
                    public void destroyItem(ViewGroup container, int position, Object object) {
                        container.removeView((View) object);
                    }

                    @Override
                    public Object instantiateItem(ViewGroup container, int position) {
                        TextView textView = new TextView(DetailActivity.this);
                        int padding = SizeUtil.dpToPx(10, getApplicationContext());
                        textView.setPadding(padding, padding, padding, padding);
                        textView.setTextColor(Color.WHITE);
                        textView.setTextSize(10);
                        textView.setGravity(Gravity.CENTER);
                        textView.setText(list.get(position));
                        container.addView(textView);
                        return textView;
                    }

                    @Override
                    public boolean isViewFromObject(View view, Object object) {
                        return view == object;
                    }
                });

                AniUtil.animateColor(Color.TRANSPARENT, scheduleEvent.color, ANIMATION_DURATION, playViewPager);

                playViewPager.setVisibility(View.VISIBLE);
                playViewPager.setAlpha(1);

                playViewPager.play(new PlayViewPager.OnEndListener() {
                    @Override
                    public void onEnd() {
                        goneWithAnimation();
                    }
                });
            }
        });


    }


    @Override
    public void onBackPressed() {
        if (playViewPager.getVisibility() == View.VISIBLE) {
            playViewPager.cancel();
            goneWithAnimation();
        } else {
            super.onBackPressed();
        }
    }

    private void goneWithAnimation() {
        AniUtil.animateColor(scheduleEvent.color, Color.TRANSPARENT, ANIMATION_DURATION, playViewPager);
        AniUtil.animate(ANIMATION_DURATION, new AniUtil.ProgressListener() {
            @Override
            public void onGoing(float value) {
                playViewPager.setAlpha(1 - value);
            }

            @Override
            public void onStart() {

            }

            @Override
            public void onEnd() {
                playViewPager.setVisibility(View.GONE);
                playViewPager.removeAllViews();
                AniUtil.popupUpFloatingBtn(vFab);
            }
        });
    }

    public int getTotalDay() {
        return (int) ((System.currentTimeMillis() - DateUtil.getDayStartTime(scheduleEvent.startTime)) / DateUtil.DAY_MILISECOND);
    }

    public int getCompleteNum(List<EventRecord> list) {
        int sum = 0;
        for (EventRecord eventRecord : list) {
            if (eventRecord.state == EventConstants.STATE_COMPLETE || eventRecord.state == EventConstants.STATE_MAKE_UP || eventRecord.state == EventConstants.STATE_AMOST_COMPLETE)
                sum++;
        }
        return sum;
    }

    private int getFailInHalfNum(List<EventRecord> eventRecordList) {
        int sum = 0;
        for (EventRecord eventRecord : eventRecordList) {
            if (eventRecord.state == EventConstants.STATE_FAIL_IN_THE_MIDDLE)
                sum++;
        }
        return sum;
    }

    private int getLazyNum(List<EventRecord> eventRecordList) {
        int sum = 0;
        for (EventRecord eventRecord : eventRecordList) {
            if (eventRecord.state == EventConstants.STATE_LAZY)
                sum++;
        }
        return sum;
    }

    private int getBuzyNum(List<EventRecord> eventRecordList) {
        int sum = 0;
        for (EventRecord eventRecord : eventRecordList) {
            if (eventRecord.state == EventConstants.STATE_TOO_BUSY)
                sum++;
        }
        return sum;
    }

    private int getMakeUpNum(List<EventRecord> eventRecordList) {
        int sum = 0;
        for (EventRecord eventRecord : eventRecordList) {
            if (eventRecord.state == EventConstants.STATE_MAKE_UP)
                sum++;
        }
        return sum;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_FRESH_DATA && resultCode == RESULT_OK) {
            scheduleEvent = ScheduleEventDao.getById(scheduleEvent.id);
            if (scheduleEvent == null) {
                finish();
            } else {
                setUpUi();
            }
        }
    }
}
